package com.shuangti.webdemo.intercepter;

import com.shuangti.webdemo.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    //目标方法执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求路径
        String requestURI = request.getRequestURI();
        //2.判断是否是/login请求，如果是放行，如果不是拦截，进行token判断验证
        if (requestURI.contains("/login")){
            log.info("是登录方法，放行");

            return true;
        }
        //3.获取请求头中的token看是否存在，不存在就是没登录返回错误信息401，存在，验证
        String token = request.getHeader("token");
        if (token == null && token.isEmpty()){
            //返回错误信息
            response.setStatus(401);
            return false;
        }

        //4.进行token验证，成功放行，失败，返回错误信息401
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("令牌非法");
            response.setStatus(401);
            return false;
        }
        //放行
        log.info("令牌合法，放行");
        return true;
    }

    //目标方法执行后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    //拦截器结束后实现的方法

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
